package com.atxiaodei.kabudarpc.client;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;

/**
 * @ClassName ReferenceInvokeProxy
 * @Deacription TODO
 * @Author 卡布达
 * @Date 2021/10/31 16:45
 * @Version 1.0
 **/
// BeanPostProcessor bean的生命周期相关的扩展，容器启动初始化实例之前就调用的，用来修改bean
@Configuration
public class ReferenceInvokeProxy implements BeanPostProcessor {

    @Autowired
    private RemoteInvocationHandler remoteInvocationHandler;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Field[] declaredFields = bean.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            if (declaredField.isAnnotationPresent(KabudaReference.class)) {
                declaredField.setAccessible(true);

                Object object=Proxy.newProxyInstance(declaredField.getType().getClassLoader(),new Class<?>[]{declaredField.getType()},remoteInvocationHandler);
                try {
                    declaredField.set(bean,object);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return bean;
    }
}
